#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查未使用的Java代码
"""
import os
import re
from pathlib import Path

def find_java_files(directory):
    """查找所有Java文件"""
    java_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.java'):
                java_files.append(os.path.join(root, file))
    return java_files

def get_class_name_from_file(file_path):
    """从文件路径获取类名"""
    file_name = os.path.basename(file_path)
    class_name = file_name[:-5]  # 移除.java扩展名
    return class_name

def is_class_used(class_name, java_files):
    """检查类是否在其他文件中被使用"""
    pattern = re.compile(r'\b' + re.escape(class_name) + r'\b')
    
    for file_path in java_files:
        # 跳过自身文件
        if get_class_name_from_file(file_path) == class_name:
            continue
            
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                
                # 检查import语句或直接使用
                if re.search(r'import.*' + class_name, content) or pattern.search(content):
                    return True
        except Exception as e:
            print(f"Error reading {file_path}: {e}")
            continue
            
    return False

def check_interfaces_implementation(class_name, java_files):
    """检查接口是否有实现类"""
    # 简单检查，查找"implements"关键字
    for file_path in java_files:
        # 跳过自身文件
        if get_class_name_from_file(file_path) == class_name:
            continue
            
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                
                # 检查implements语句
                if re.search(r'implements.*' + class_name, content):
                    return True
        except Exception as e:
            continue
            
    return False

def main():
    """主函数"""
    java_last_war_dir = Path(__file__).parent.parent.parent
    java_files = find_java_files(java_last_war_dir)
    
    print(f"检查 {len(java_files)} 个Java文件中的未使用代码...\n")
    
    unused_classes = []
    unused_interfaces = []
    
    for file_path in java_files:
        class_name = get_class_name_from_file(file_path)
        
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                
                # 跳过Application类和测试类
                if class_name.endswith('Application') or class_name.endswith('Test'):
                    continue
                    
                # 检查是否是接口
                is_interface = 'interface ' + class_name in content
                
                # 检查是否是抽象类
                is_abstract = 'abstract class ' + class_name in content
                
                # 跳过主要的类和框架类
                if class_name in ['Message', 'MessageHeader', 'MessageConstants']:
                    continue
                
                if is_interface:
                    has_implementation = check_interfaces_implementation(class_name, java_files)
                    if not has_implementation:
                        unused_interfaces.append((file_path, class_name))
                else:
                    is_used = is_class_used(class_name, java_files)
                    if not is_used:
                        unused_classes.append((file_path, class_name))
                        
        except Exception as e:
            print(f"Error processing {file_path}: {e}")
    
    print("\n=== 未使用的类 ===")
    for file_path, class_name in unused_classes:
        rel_path = os.path.relpath(file_path, java_last_war_dir)
        print(f"{rel_path}")
    
    print(f"\n=== 未使用的接口 ===")
    for file_path, class_name in unused_interfaces:
        rel_path = os.path.relpath(file_path, java_last_war_dir)
        print(f"{rel_path}")
    
    print(f"\n统计:")
    print(f"未使用的类: {len(unused_classes)}")
    print(f"未使用的接口: {len(unused_interfaces)}")

if __name__ == "__main__":
    main()